package com.py.outbound.service.impl;

import java.util.Date;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.py.outbound.domain.DateBeginEnd;
import com.py.outbound.domain.StatisticsDate;
import com.py.outbound.domain.WhOutbound;
import com.py.outbound.mapper.WhOutboundMapper;
import com.py.outbound.domain.*;
import com.py.outbound.mapper.*;
import com.py.outbound.service.IWhOutboundService;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 出库管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-12-16
 */
@Service
public class WhOutboundServiceImpl implements IWhOutboundService
{
    @Resource
    private WhOutboundMapper whOutboundMapper;

    @Resource
    private WhOutboundDetailsMapper whOutboundDetailsMapper;



    /**
     * 代办事项（代执行）
     */
    @Override
    public List<WhOutbound> selectExecute() {
        return whOutboundMapper.selectExecute();
    }

    /**
     * 代表事项（待审核）
     */
    @Override
    public List<WhOutbound> selectToExamine() {
        return whOutboundMapper.selectToExamine();
    }

    /**
     * 概况
     */
    @Override
    public List<WhOutbound> selectOverview(Date time) {
        return whOutboundMapper.selectOverview(time);
    }

    /**
     * 出库排名
     */
    @Override
    public List<WhOutbound> selectWhOutboundRanking() {
        return whOutboundMapper.selectWhOutboundRanking();
    }

    /**
     * 出库统计
     * @param dateBeginEnd
     * @return
     */
    @Override
    public StatisticsDate selectWhOutboundStatistics(DateBeginEnd dateBeginEnd) {
        List<LocalDate> dateList = new ArrayList<>();
        long days = ChronoUnit.DAYS.between(dateBeginEnd.getBegin(), dateBeginEnd.getEnd());
        dateList.add(dateBeginEnd.getBegin());
        System.out.println("当前时间：" + dateBeginEnd.getBegin());
        if (!dateBeginEnd.getBegin().equals(dateBeginEnd.getEnd())) {
            for (int i = 0; i <days; i++) {
                dateList.add(dateBeginEnd.getBegin().plusDays(i + 1));
            }
        }

        List<BigDecimal> priceList = new ArrayList<>(dateList.size());
        List<Integer> quantityList = new ArrayList<>(dateList.size());
        for (int i = 0; i < dateList.size(); i++) {
            priceList.add(BigDecimal.ZERO); // 初始化为零
            quantityList.add(0); // 初始化为零
        }

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            System.out.println("beginTime:" + beginTime + "endTime:" + endTime);
            List<WhOutbound> whOutboundList = whOutboundMapper.selectWhOutboundStatistics(beginTime, endTime);
            BigDecimal totalPrice = BigDecimal.ZERO;
            Integer totalQuantity = 0;
            for (WhOutbound whOutbound : whOutboundList) {
                totalPrice = totalPrice.add(whOutbound.getUnitPrice()); // 累加金额
                totalQuantity += whOutbound.getOutStorage(); // 累加数量
            }
            priceList.set(dateList.indexOf(date), totalPrice); // 设置对应日期的金额
            quantityList.set(dateList.indexOf(date), totalQuantity); // 设置对应日期的数量
        }

        return new StatisticsDate.Builder()
                .dateList(dateList)
                .price(priceList)
                .quantity(quantityList)
                .build();
    }

    @Resource
    private OdSaleDetailsMapper odSaleDetailsMapper;

    @Resource
    private OdSaleMapper odSaleMapper;

    @Resource
    private InRejectedMapper inRejectedMapper;

    @Resource
    private RejectedDetailsMapper rejectedDetailsMapper;

    /**
     * 查询出库管理
     * 
     * @param outboundId 出库管理主键
     * @return 出库管理
     */
    @Override
    public WhOutbound selectWhOutboundByOutboundId(Long outboundId)
    {
        return whOutboundMapper.selectWhOutboundByOutboundId(outboundId);
    }

    /**
     * 查询出库管理列表
     * 
     * @param whOutbound 出库管理
     * @return 出库管理
     */
    @Override
    public List<WhOutbound> selectWhOutboundList(WhOutbound whOutbound)
    {
        return whOutboundMapper.selectWhOutboundList(whOutbound);
    }

    /**
     * 新增出库管理
     * 
     * @param whOutbound 出库管理
     * @return 结果
     */
    @Override
    public int insertWhOutbound(WhOutbound whOutbound)
    {
        whOutbound.setCreateBy(SecurityUtils.getUsername());
        whOutbound.setCreateTime(DateUtils.getNowDate());
        System.out.println("创建让");
        System.out.println(whOutbound.getCreateBy() + "\t" + SecurityUtils.getUsername());
        System.out.println(SecurityUtils.getUsername());
        return whOutboundMapper.insertWhOutbound(whOutbound);
    }

    /**
     * 修改出库管理
     * 
     * @param whOutbound 出库管理
     * @return 结果
     */
    @Override
    public int updateWhOutbound(WhOutbound whOutbound)
    {
        whOutbound.setUpdateTime(DateUtils.getNowDate());
        return whOutboundMapper.updateWhOutbound(whOutbound);
    }

    /**
     * 批量删除出库管理
     * 
     * @param outboundIds 需要删除的出库管理主键
     * @return 结果
     */
    @Override
    public int deleteWhOutboundByOutboundIds(Long[] outboundIds)
    {
        return whOutboundMapper.deleteWhOutboundByOutboundIds(outboundIds);
    }

    /**
     * 删除出库管理信息
     * 
     * @param outboundId 出库管理主键
     * @return 结果
     */
    @Override
    public int deleteWhOutboundByOutboundId(Long outboundId)
    {
        return whOutboundMapper.deleteWhOutboundByOutboundId(outboundId);
    }

    @Override
    public int outboundStatus(WhOutbound outbound) {
        outbound.setReviewerTime(new Date());
        Integer result = whOutboundMapper.outboundStatus(outbound);

        System.out.println(outbound.getOutboundStatus());
        if (outbound.getOutboundStatus().equals("1")){
            return result;
        }
        System.out.println("进来了");
        System.out.println(outbound);
        String status = "6";
        if (result > 0){
            List<WhOutboundDetails> list = whOutboundDetailsMapper.selectWhOutboundDetailsByOutBoundCode(outbound.getOutboundCode());
            if (list != null){
                for (WhOutboundDetails whOutboundDetails : list) {
                    System.out.println("循环list");
                    System.out.println(list);
                    WhInventory whInventory = new WhInventory();
                    whInventory.setLocationCode(whOutboundDetails.getLocationCode());
                    whInventory.setProductCode(whOutboundDetails.getProductCode());
                    whInventory.setPendingOut(Math.toIntExact(whOutboundDetails.getOutboundNumber()));
                    System.out.println(whInventory);
                    //修改待出库数量
                    whOutboundDetailsMapper.updatePendingOutNumJian(whInventory);
                    System.out.println("修改待出库数量成功");
                    System.out.println();
                    Long num = whOutboundDetails.getOutboundNumber();//本次出库数量
                    String code = outbound.getRelatedNumber();//订单编号
                    String productCode = whOutboundDetails.getProductCode();//商品编号

                    System.out.println("修改待出库数量：" + num + "\t订单编号：" + code + "\t商品编号：" + productCode);
                    //修改订单已出库数量
                    if (outbound.getOutboundType().equals("0")){

                        System.out.println();
                        odSaleDetailsMapper.updateSaleDetails(num,code,productCode);
                        System.out.println("修改销售出库数量");
                        System.out.println();
                    }else{
                        //获取进货退货单

                        //更改进货单出库数量

                        InRejected inRejected = inRejectedMapper.selectInRejected(code);

                        System.out.println("进货单");

                        System.out.println(inRejected);

                        inRejectedMapper.updatePurchaseRejectedNumber(num,inRejected.getPhCode(),productCode);
                        System.out.println("进货单修改成功");

                        //修改进货退货单未出库数量
                        rejectedDetailsMapper.updateDetailsRejectedNum(num,code,productCode);
                        System.out.println("修改进货退货单未出库数量");
                    }
                }

                if (outbound.getOutboundType().equals("0")){
                    //获取销售订单
                    int num = odSaleMapper.selectOdSale(outbound.getRelatedNumber());
                    //获取销售详情单出库总数
                    int count = odSaleDetailsMapper.numCount(outbound.getRelatedNumber());

                    System.out.println(count);
                    status = num == count ? "4" : "6";
                    System.out.println("销售单");
                    System.out.println(status);
                    System.out.println("出库总数：" + count);
                    odSaleMapper.updateOdSale(outbound.getRelatedNumber(),status);
                }else{
                    status = rejectedDetailsMapper.rejectedCount(outbound.getRelatedNumber()) == 0 ? "4" : "6";
                    System.out.println("退货单");
                    System.out.println(status);
                    inRejectedMapper.updateInRejected(outbound.getRelatedNumber(),status);
                };

                System.out.println("修改成功");
            }
        }
        return result;
    }
}
